<?php

namespace app\controller\admin;

use think\facade\Db;
use think\facade\View;
use think\facade\Request;

class Link extends Common
{
    public function index($act = null)
    {
        if ($act == 'del') {
            if (!Request::isPost()) {
                return error(lang('参数错误'));
            }
            $ids = input('post.');

            if (!empty($ids)) {
                $r = Db::name('link')->delete($ids['ids']);
                if ($r) {
                    add_log('删除友情链接，ID：'.implode(',', $ids['ids']), $this->request->user->username);
                    return success(lang('操作成功'), url('admin/link/index'));
                }
            }

            return error(lang('请勾选需要删除的选项'));
        }

        $list = Db::name('link')->order('o asc')->paginate(25);
        View::assign('list', $list);
        return View::fetch();
    }

    public function add()
    {
        return View::fetch('form');
    }

    public function edit($id)
    {
        $id = intval($id);
        $link = Db::name('link')->where(['id' => $id])->find();
        if (!$link) {
            return error(lang('参数错误'));
        }
        View::assign('link', $link);
        return View::fetch('form');
    }

    public function save()
    {
        if (!Request::isPost()) {
            return error(lang('参数错误'));
        }

        $data = input('post.');
        if ($data['title'] == '') {
            return error(lang('标题不能为空'));
        }

        $data['id'] = intval($data['id']);
        $data['o'] = intval($data['o']);
        if ($data['id']) {
            $r = Db::name('link')->where(['id' => $data['id']])->update($data);
            add_log('编辑友情链接，ID：'.$data['id'], $this->request->user->username);
        } else {
            unset($data['id']);
            $r = Db::name('link')->insert($data);
            add_log('新增友情链接，标题：'.$data['title'], $this->request->user->username);
        }
        if ($r) {
            return success(lang('操作成功'), url('admin/link/index'));
        } else {
            return error(lang('系统错误'));
        }
    }
}
